package com.mhr.ai.cr.service

import com.google.gson.Gson
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.mhr.ai.cr.model.AIReviewResult
import com.mhr.ai.cr.settings.AISettingsState

/**
 * AI 代码审核服务
 * 支持多个AI提供商进行代码审核
 */
@Service(Service.Level.PROJECT)
class AICodeReviewService(private val project: Project) {
    
    private val logger = thisLogger()
    private val gson = Gson()
    
    /**
     * 审核代码变更
     */
    fun reviewCode(diffContent: String, filePath: String): AIReviewResult {
        return try {
            val settings = AISettingsState.getInstance(project)
            
            // 检查配置是否有效
            if (!settings.enabled) {
                return AIReviewResult(
                    overallScore = 5,
                    issues = listOf("⚠️ AI 审核功能已禁用"),
                    suggestions = listOf("💡 请在设置中启用 AI 审核功能"),
                    summary = "AI 审核功能已禁用"
                )
            }
            
            if (!settings.isConfigValid()) {
                return AIReviewResult(
                    overallScore = 5,
                    issues = listOf("⚠️ AI 配置无效，请检查 API 密钥和模型设置"),
                    suggestions = listOf("💡 请在 Settings → Tools → AI 代码审核 中配置 API 密钥"),
                    summary = "需要配置 API 密钥和模型才能使用 AI 审核功能"
                )
            }
            
            val prompt = buildReviewPrompt(diffContent, filePath, settings)
            val response = callAIProvider(prompt, settings)
            parseAIResponse(response)
        } catch (e: Exception) {
            logger.warn("AI代码审核失败", e)
            AIReviewResult(
                overallScore = 0,
                issues = listOf("AI服务调用失败: ${e.message}"),
                suggestions = listOf("💡 请检查网络连接和 API 配置"),
                summary = "审核失败，请检查网络连接和API配置"
            )
        }
    }
    
    /**
     * 构建审核提示词
     */
    private fun buildReviewPrompt(diffContent: String, filePath: String, settings: AISettingsState): String {
        val reviewLevelText = when (settings.reviewLevel) {
            "basic" -> "进行基础的代码审核，重点关注明显的问题"
            "strict" -> "进行严格的代码审核，详细分析所有潜在问题"
            else -> "进行标准的代码审核，平衡详细程度和实用性"
        }
        
        return """
请作为一个资深的代码审核专家，对以下代码变更进行详细审核。

审核要求：$reviewLevelText

文件路径: $filePath

代码变更内容:
```
$diffContent
```

请从以下几个方面进行审核：
1. 代码质量和规范性
2. 潜在的bug和安全问题  
3. 性能优化建议
4. 可维护性和可读性
5. 最佳实践建议

请以JSON格式返回审核结果，包含以下字段：
- overallScore: 总体评分(1-10分)
- issues: 发现的问题列表(如果没有问题则为空数组)
- suggestions: 改进建议列表(如果没有建议则为空数组)
- summary: 总结性评价

示例格式：
{
  "overallScore": 8,
  "issues": ["问题1", "问题2"],
  "suggestions": ["建议1", "建议2"],
  "summary": "总体评价"
}

请确保返回有效的JSON格式，不要包含其他文本。
        """.trimIndent()
    }
    
    /**
     * 调用AI提供商
     * 根据用户配置动态选择提供商
     */
    private fun callAIProvider(prompt: String, settings: AISettingsState): String {
        val provider = settings.getCurrentProvider()
            ?: throw IllegalStateException("未找到配置的AI提供商: ${settings.currentProvider}")

        val config = settings.getProviderConfig()

        return provider.reviewCode(prompt, config)
    }
    
    /**
     * 解析AI响应
     */
    private fun parseAIResponse(aiResponse: String): AIReviewResult {
        return try {
            // 尝试从响应中提取JSON部分
            val jsonStart = aiResponse.indexOf("{")
            val jsonEnd = aiResponse.lastIndexOf("}") + 1
            
            if (jsonStart >= 0 && jsonEnd > jsonStart) {
                val jsonContent = aiResponse.substring(jsonStart, jsonEnd)
                val responseMap = gson.fromJson(jsonContent, Map::class.java)
                
                AIReviewResult(
                    overallScore = (responseMap["overallScore"] as? Double)?.toInt() ?: 5,
                    issues = (responseMap["issues"] as? List<*>)?.map { it.toString() } ?: emptyList(),
                    suggestions = (responseMap["suggestions"] as? List<*>)?.map { it.toString() } ?: emptyList(),
                    summary = responseMap["summary"]?.toString() ?: "AI审核完成"
                )
            } else {
                // 如果无法解析JSON，返回原始响应作为总结
                AIReviewResult(
                    overallScore = 7,
                    issues = emptyList(),
                    suggestions = emptyList(),
                    summary = aiResponse
                )
            }
        } catch (e: Exception) {
            logger.warn("解析AI响应失败", e)
            AIReviewResult(
                overallScore = 5,
                issues = listOf("解析AI响应失败: ${e.message}"),
                suggestions = emptyList(),
                summary = "AI响应: $aiResponse"
            )
        }
    }
    
    /**
     * 获取当前配置状态
     */
    fun getConfigStatus(): String {
        val settings = AISettingsState.getInstance(project)
        return when {
            !settings.enabled -> "AI 审核已禁用"
            !settings.isConfigValid() -> "配置无效：缺少 API 密钥或模型设置"
            else -> {
                val providerName = settings.getCurrentProviderType()?.displayName ?: "未知"
                val modelName = settings.getModelDisplayName(settings.getCurrentModel())
                "配置正常：$providerName - $modelName"
            }
        }
    }
    
    /**
     * 测试 API 连接
     */
    fun testConnection(): AIReviewResult {
        return try {
            val settings = AISettingsState.getInstance(project)
            val provider = settings.getCurrentProvider()
                ?: throw IllegalStateException("未找到配置的AI提供商")

            val config = settings.getProviderConfig()
            val isConnected = provider.testConnection(config)

            if (isConnected) {
                AIReviewResult(
                    overallScore = 10,
                    issues = emptyList(),
                    suggestions = emptyList(),
                    summary = "API 连接测试成功"
                )
            } else {
                AIReviewResult(
                    overallScore = 0,
                    issues = listOf("连接测试失败"),
                    suggestions = listOf("💡 请检查API密钥和网络连接"),
                    summary = "API 连接测试失败"
                )
            }
        } catch (e: Exception) {
            AIReviewResult(
                overallScore = 0,
                issues = listOf("连接测试失败: ${e.message}"),
                suggestions = listOf("💡 请检查API密钥和网络连接"),
                summary = "API 连接测试失败"
            )
        }
    }
}